<template>
  <view class="container">
    <!-- 轮播图表部分 -->
    <view class="chart-wrapper">
      <swiper 
        :indicator-dots="true" 
        :autoplay="true" 
        :interval="5000" 
        :circular="true"
        class="swiper-box"
        @change="handleSwiperChange"
      >
        <swiper-item v-for="(item, index) in chartList" :key="index">
          <view class="chart-title">{{ item.title }}</view>
          <qiun-data-charts 
            type="pie"
            :opts="chartOptsList[index]"
            :chartData="formatChartData(item)"
            :canvasId="'pieChart'+index"
            class="chart"
            @click="handleChartClick"
          />
        </swiper-item>
      </swiper>
    
      <view v-if="selectedImages.length > 0" class="image-container-wrapper">
        <view class="category-title">{{ selectedCategory }}</view>
        <view class="image-container">
          <scroll-view class="image-scroll" scroll-y>
            <view class="image-grid">
              <view v-for="(item, index) in selectedImages" :key="index" class="image-item-wrapper" @click="showActionSheet(item)">
                <image :src="formatImageUrl(item.image)" mode="aspectFill" class="cloth-image"/>
                <view class="idle-days" v-if="item.idleDays > 0">闲置{{ item.idleDays }}天</view>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    
      <!-- 动作菜单 -->
      <view v-if="showActionSheetFlag" class="action-sheet-mask" @click="hideActionSheet">
        <view class="action-sheet" @click.stop>
          <view class="action-sheet-title">选择操作</view>
          <view class="action-sheet-options">
            <view class="action-sheet-option" @click="handleDonate">捐赠</view>
            <view class="action-sheet-option" @click="handleSecondHand">二手转卖</view>
            <view class="action-sheet-option" @click="hideActionSheet">取消</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import setting from '../../setting';
export default {
  data() {
    return {
		userId:null,
      currentChartIndex: 0,
      chartList: [
        {
          title: '衣物使用比例',
          data: [
            { name: '总常用', data: 0 },
            { name: '总闲置', data: 0 }
          ],
          colors: ['#FFA500', '#FFD700']
        },
        {
          title: '上衣数据分析',
          data: [
            { name: '上衣常用', data: 0 },
            { name: '上衣闲置', data: 0 }
          ],
          colors: ['#ECC0EF', '#EE8AF8']
        },
        {
          title: '裤子数据分析',
          data: [
            { name: '裤子常用', data: 0 },
            { name: '裤子闲置', data: 0 }
          ],
          colors: ['#FFAEC9', '#EF66BF']
        },
        {
          title: '裙子数据分析',
          data: [
            { name: '裙子常用', data: 0 },
            { name: '裙子闲置', data: 0 }
          ],
          colors: ['#BFEFC6', '#9DF8AF']
        },
        {
          title: '鞋子数据分析',
          data: [
            { name: '鞋子常用', data: 0 },
            { name: '鞋子闲置', data: 0 }
          ],
          colors: ['#EFBBBB', '#EF778A']
        },
        {
          title: '其他数据分析',
          data: [
            { name: '其他常用', data: 0 },
            { name: '其他闲置', data: 0 }
          ],
          colors: ['#A4B1EF', '#3988EF']
        }
      ],
      chartOpts: {
        title: { 
          name: '',  
          show: false 
        },
        legend: { 
          show: true,
          position: 'bottom',
          fontSize: 12
        },
        tooltip: { 
          show: true,
          backgroundColor: 'rgba(0,0,0,0.7)'
        },
        dataLabel: {
          fontSize: 14,
          color: '#fff'
        }
      },
      selectedCategory: '',
      yiwu: [],
      chartWidth: 375,
      chartHeight: 300,
      showActionSheetFlag: false,
      currentImageItem: null
    };
  },
  computed: {
    chartOptsList() {
      return this.chartList.map(item => ({
        ...this.chartOpts,
        title: { ...this.chartOpts.title, name: item.title },
        color: item.colors
      }));
    },
    selectedImages() {
        if (!this.selectedCategory) {
          return [];
        }
        
        const result = this.yiwu.filter(item => {
          const idleDays = Number(item.idleDays) || 0;
          
          if (this.selectedCategory === '总常用') {
            return idleDays <= 90;
          } else if (this.selectedCategory === '总闲置') {
            return idleDays > 90;
          } else {
            const category = this.selectedCategory.replace('常用', '').replace('闲置', '');
            const isIdle = this.selectedCategory.includes('闲置');
            return item.category === category && 
                  ((isIdle && idleDays > 90) || (!isIdle && idleDays <= 90));
          }
        });
        
       // console.log('筛选结果:', result); // 调试输出
        return result;
      }
  },
  created() {
	  //console.log('组件创建，开始获取数据');
	    this.fetchClothesData(); 
	    // 测试用 - 模拟点击事件（延迟执行确保数据加载完成）
	    setTimeout(() => {
	      //console.log('模拟点击"总常用"分类');
	      this.selectedCategory = '总常用';
	      // 使用JSON.stringify展开对象查看完整数据
	    }, 1000); // 延长延迟时间确保数据加载
  },
  methods: {
	formatImageUrl(url) {
	  if (!url) return ""
	  // 处理不同类型的URL
	  if (url.startsWith("blob:")) {
	    // blob URL 可能已经失效，需要特殊处理
	    // 尝试从服务器获取图片 - 假设图片名称在URL的最后部分
	    const filename = url.split("/").pop()
	    if (filename) {
	      const serverUrl = `${setting.url}/uploads/clothes/${filename}`
	      return serverUrl
	    }
	    return url // 如果无法提取文件名，保留原始URL
	  } else if (url.startsWith("/uploads/")) {
	    // 服务器上的图片添加服务器地址前缀
	    const formattedUrl = `${setting.url}${url}`
	    return formattedUrl
	  } else if (!url.startsWith("http") && !url.startsWith("/static/")) {
	    // 其他相对路径情况
	    const formattedUrl = `${setting.url}/uploads/clothes/${url}`
	    return formattedUrl
	  }
	
	  // 已经是完整URL
	  return url
	},
	 async fetchClothesData() {
	     try {
	       this.loading = true;
	       this.userId = uni.getStorageSync('user_id');
	       if (!this.userId) {
	         throw new Error('用户未登录');
	       }
	 
	       const res = await new Promise((resolve, reject) => {
	         uni.request({
	           url: setting.url+'/api/clothesList',
	           method: 'POST',
	           data: { user_id: this.userId },
	           header: { 'Content-Type': 'application/json' },
	           success: (res) => resolve(res),
	           fail: (err) => reject(err)
	         });
	       });
	 
	       if (res.statusCode === 200) {
	         const responseData = res.data;
	         //console.log('API返回原始数据:', JSON.stringify(responseData, null, 2));
	         
	         if (responseData.data?.length > 0) {
	           this.yiwu = responseData.data.map(item => ({
	             image: item.image_url,
	             category: item.category,
	             idleDays: Number(item.idle_days) || 0,
	           }));
	           // 初始化图表数据
	           this.updateChartData();
	         }
	       }
	     } catch (error) {
	       console.error('获取衣物数据失败:', error);
	       this.yiwu = this.getDefaultClothesData();
	       this.updateChartData();
	     } finally {
	       this.loading = false;
	     }
	   },
	  updateChartData() {
	      // 更新图表数据
	      this.chartList.forEach(chart => {
	        chart.data.forEach(item => item.data = 0);
	      });
	      
	      this.yiwu.forEach(item => {
	        const isIdle = item.idleDays > 90;
	        
	        // 更新总数据
	        this.chartList[0].data[isIdle ? 1 : 0].data++;
	        
	        // 更新分类数据
	        const categoryIndex = this.chartList.findIndex(chart => 
	          chart.title.includes(item.category)
	        );
	        if (categoryIndex !== -1) {
	          this.chartList[categoryIndex].data[isIdle ? 1 : 0].data++;
	        }
	      });
	      
	      //console.log('更新后的图表数据:', JSON.stringify(this.chartList, null, 2));
	    },
	  getDefaultClothesData() {
	    return [
	      { 
	        image: '/static/shangyi.jpg',
	        category: '上衣',
	        idleDays: 30,
	        brand: '默认品牌',
	        color: '默认颜色',
	        size: 'M',
	        material: '棉',
	        season: '四季',
	        fit: '标准',
	        subcategory: '默认子类'
	      },
	    ];
	  },
calculateChartData() {
  // 确保图表容器存在
  if (!this.$refs.chartContainer) return;
  
  // 使用setTimeout确保DOM更新完成
  setTimeout(() => {
    const ctx = uni.createCanvasContext('myChart', this);
    // 检查ctx是否有效
    if (ctx && typeof ctx.draw === 'function') {
      // 绘制图表逻辑...
      ctx.draw();
    } else {
      console.error('Canvas上下文获取失败');
      // 延迟重试
      setTimeout(this.calculateChartData, 500);
    }
  }, 100);
},
    formatChartData(item) {
      return {
        series: item.data
      };
    },
    handleSwiperChange(e) {
      this.currentChartIndex = e.detail.current;
    },
    handleChartClick(e) {
       if (e && e.detail) {
         const clickedCategory = this.getCategoryFromCoordinates(e.detail.x, e.detail.y);
         if (clickedCategory) {
          // console.log('点击的分类:', clickedCategory); // 调试输出
           this.selectedCategory = clickedCategory;
           
           // 调试输出筛选结果
           // console.log('筛选条件:', {
           //   category: this.selectedCategory,
           //   items: this.yiwu.map(i => ({
           //     category: i.category, 
           //     idleDays: i.idleDays
           //   }))
           // });
           
           uni.pageScrollTo({
             scrollTop: 400,
             duration: 500
           });
         }
       }
     },
    getCategoryFromCoordinates(x, y) {
      const centerX = this.chartWidth / 2;
      const centerY = this.chartHeight / 2;
      const radius = Math.min(centerX, centerY);
      const relativeX = x - centerX;
      const relativeY = y - centerY;
      const distance = Math.sqrt(relativeX * relativeX + relativeY * relativeY);
      if (distance > radius) {
        return null;
      }
      let angle = Math.atan2(relativeY, relativeX) * 180 / Math.PI;
      if (angle < 0) {
        angle += 360;
      }
      const totalData = this.chartList[this.currentChartIndex].data.reduce((sum, item) => sum + item.data, 0);
      if (totalData === 0) return null;
      
      const dataAngles = this.chartList[this.currentChartIndex].data.map(item => (item.data / totalData) * 360);
      let cumulativeAngle = 0;
      for (let i = 0; i < dataAngles.length; i++) {
        const startAngle = cumulativeAngle;
        const endAngle = cumulativeAngle + dataAngles[i];
        if (angle >= startAngle && angle < endAngle) {
          return this.chartList[this.currentChartIndex].data[i].name;
        }
        cumulativeAngle = endAngle;
      }
      return null;
    },
    showActionSheet(item) {
      this.currentImageItem = item;
      this.showActionSheetFlag = true;
    },
    hideActionSheet() {
      this.showActionSheetFlag = false;
    },
    handleDonate() {
      uni.showToast({
        title: '捐赠功能正在开发中',
        icon: 'none'
      });
      this.hideActionSheet();
    },
    handleSecondHand() {
      uni.showToast({
        title: '二手转卖功能正在开发中',
        icon: 'none'
      });
      this.hideActionSheet();
    }
  }
};
</script>

<style scoped>
.chart-title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding: 20rpx 0;
  position: relative;
}
.chart-title::after {
  content: '';
  display: block;
  width: 60px;
  height: 2px;
  background: #FFA500;
  margin: 8px auto 0;
}
.chart-wrapper {
  width: 90%;
  height: 630rpx;
  margin: 20rpx auto;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
}
.swiper-box {
  width: 100%;
  height: 100%;
}
.swiper-item {
  padding: 20rpx;
  box-sizing: border-box;
}
.chart {
  width: 100%;
  height: 500rpx;
}

/deep/ .uni-swiper-dots {
  bottom: 20rpx !important;
}
/deep/ .uni-swiper-dot {
  width: 16rpx !important;
  height: 16rpx !important;
  background: #e0e0e0 !important;
}
/deep/ .uni-swiper-dot-active {
  background: #FFA500 !important;
}
/deep/ .qiun-charts {
  cursor: pointer;
}

.image-container-wrapper {
  margin-top: 10rpx;
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);
  overflow: hidden;
}
.category-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding: 20rpx;
  text-align: center;
  border-bottom: 1px solid #eee;
}
.image-container {
  height: 800rpx;
}
.image-scroll {
  height: 100%;
}
.image-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx;
}
.image-item-wrapper {
  width: 33.333%;
  height: 200rpx;
  margin-bottom: 20rpx;
  border-radius: 8rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
  position: relative;
}
.cloth-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.idle-days {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 12px;
  text-align: center;
  padding: 4rpx 0;
}

/* 动作菜单样式 */
.action-sheet-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 999;
}
.action-sheet {
  background: #fff;
  width: 100%;
  border-radius: 20rpx 20rpx 0 0;
  overflow: hidden;
}
.action-sheet-title {
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  border-bottom: 1px solid #eee;
}
.action-sheet-options {
  display: flex;
  flex-direction: column;
}
.action-sheet-option {
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-size: 28rpx;
  border-top: 1px solid #eee;
}
.action-sheet-option:first-child {
  border-top: none;
}
</style>